/**
 * 
 */
package org.t2.backstage.module.gameserver;

import org.banish.sql.core.util.QuerySet;
import org.gaming.backstage.PageData;
import org.gaming.backstage.interceptor.RoleContext;
import org.gaming.backstage.module.user.model.User;
import org.gaming.backstage.module.user.service.UserService;
import org.gaming.service.apidoc.annotation.ApiDocument;
import org.gaming.service.asserts.Asserts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.t2.backstage.module.TipsCode;
import org.t2.backstage.module.gameserver.from.GameDbForm;
import org.t2.backstage.module.gameserver.model.GameDb;
import org.t2.backstage.module.gameserver.service.DataBaseManager;
import org.t2.backstage.module.gameserver.service.GameDbService;
import org.t2.backstage.module.gameserver.struct.GameServerQuery;

/**
 * @author YY
 *
 */
@Controller
public class GameDbController {

	@Autowired
	private GameDbService gameDbService;
	@Autowired
	private UserService userService;
	@Autowired
	private DataBaseManager dataBaseManager;
	
	
	@ApiDocument("请求服务器数据库配置数据")
	@RequestMapping(value = "/gameDb/data.auth")
	@ResponseBody
	public PageData<GameDb> data(GameServerQuery query) {
		QuerySet querySet = new QuerySet();
		if(query.getPlatformId() > 0) {
			querySet.addCondition("platform_id = ?", query.getPlatformId());
		}
		if(query.getServerId() > 0) {
			querySet.addCondition("server_id = ?", query.getServerId());
		}
		querySet.limit(query.getPage(), query.getLimit());
		querySet.orderBy("order by db_name desc");
		querySet.formWhere();
		return gameDbService.query(querySet);
	}
	
	@ApiDocument("保存服务器数据，ID小于等于0时新增，大于0时修改")
	@RequestMapping(value = "/gameDb/save.authw")
	@ResponseBody
	public GameDb saveData(GameDbForm form) {
		RoleContext roleContext = userService.getCurrUser();
		User user = userService.getById(roleContext.getId());
		Asserts.isTrue(user.isSuperUser(), TipsCode.NO_SUPERUSER);
		
		GameDb gameDb = gameDbService.getDb(form.getDbName());
		if(gameDb == null) {
			gameDb = new GameDb();
			gameDb.setDbName(form.getDbName());
			gameDbService.insert(gameDb);
		}
		gameDb.setPlatformId(form.getPlatformId());
		gameDb.setServerId(form.getServerId());
		gameDb.setType(form.getType());
		gameDb.setZoneId(form.getZoneId());
		gameDb.setAlias(form.getAlias());
		gameDb.setIpPort(form.getIpPort());
		gameDb.setUser(form.getUser());
		gameDb.setPassword(form.getPassword());
		gameDb.setMinIdle(form.getMinIdle());
		gameDb.setMaxActive(form.getMaxActive());
		gameDb.setMaxWaitMillis(form.getMaxWaitMillis());
		gameDbService.update(gameDb);
		
		dataBaseManager.cleanErroDataBase();
		return gameDb;
	}
}
